import fs from 'fs'
import path from 'path'
import Express from 'express'
import bodyParser from 'body-parser'
import config from '../config'
import api from './service'
import { build } from '../config/index'

const app = new Express()

app.set('port', config.server.port)
app.use(Express.static(path.resolve(__dirname, '../dist')))
app.use(Express.static(path.resolve(__dirname, '../dist/static')))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(api)

app.get(`*`, (request, response) => {
  const html = fs.readFileSync(build.index, 'utf-8')

  response.header('Access-Control-Allow-Origin', '*')
  response.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With')
  response.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  response.header('X-Powered-By', '3.2.1')

  response.send(html)
})

app.listen(config.server.port, () => console.log(`server running http://${config.server.domain}:${config.server.port}`))
